<template>
  <cloud-dialog
    :visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-open="handleBeforeOpen"
    :before-close="handleBeforeClose">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical">
      <a-form-item
        class="mb-0!"
        field="group_id"
        label="选择分组"
        hide-asterisk
        asterisk-position="end"
        required>
        <a-select
          v-model="formData.group_id"
          placeholder="请选择分组"
          :options="groupOptions" />
      </a-form-item>
    </a-form>
  </cloud-dialog>
</template>
<script lang="ts" setup>
import { updateApiSiteBatchUpdateGroupApi } from '@/apis/modules/site/site'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
interface IProps {
  visible: boolean
  groupIds?: string[]
  groupOptions: LabelValue[]
}
const props = withDefaults(defineProps<IProps>(), {
  visible: false
})
interface IEmits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}
const emits = defineEmits<IEmits>()

const title = computed(() => (props.groupIds!.length ? '编辑分组' : '添加分组'))
const formRef = ref<FormInstance>()
const formData = ref({
  group_id: '',
  ids: [] as string[]
})
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    group_id: [
      {
        required: true,
        message: '请选择分组'
      }
    ]
  }
})
const handleBeforeOpen = async () => {
  formData.value.ids = props.groupIds! as string[]
}
const handleBeforeClose = async () => {
  await formRef.value?.resetFields()
  emits('update:visible', false)
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error) return false
  // 提交表单
  await updateApiSiteBatchUpdateGroupApi({ ...formData.value }).then(() => {
    ToastUtils.success('操作成功')
    emits('update:visible', false)
    emits('refresh')
  })
}
</script>

<style lang="less" scoped></style>
